package com.alpaak.common.utils;

import org.apache.commons.beanutils.BeanUtils;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * JavaBean转换器
 * 
 */
public class BeanConverter { 

	// Map --> Bean 2: 利用org.apache.commons.beanutils 工具类实现 Map --> Bean
	public static void transMap2Bean(Map<String, Object> map, Object obj) throws IllegalAccessException, InvocationTargetException {
		if (map == null || obj == null) {
			return;
		}
		BeanUtils.populate(obj, map);
	}

	// Bean --> Map 1: 利用Introspector和PropertyDescriptor 将Bean --> Map
	public static Map<String, Object> transBean2Map(Object obj)
			throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

		if (obj == null) {
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
		for (PropertyDescriptor property : propertyDescriptors) {
			String key = property.getName();
			// 过滤class属性
			if (!key.equals("class")) {
				// 得到property对应的getter方法
				Method getter = property.getReadMethod();
				Object value = getter.invoke(obj);
				map.put(key, value);
			}

		}
		return map;
	}

	//对象属性copy
	public static void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException {
		if (orig == null) {
			return;
		}

		BeanUtils.copyProperties(dest, orig);
	}
}